import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { CommonService } from '../../../../services-common/common.service';
import { financeOrderChangeArrs, secondOrderStateArrs } from '../../status.pipe';
import { partsOrderStatusArrs } from '../../../order/order.pipe';
import { FinanceOldchangeManageService } from '../finance-oldchange-manage.service';

@Component({
  selector: 'app-finance-oldchange-list',
  templateUrl: './finance-oldchange-list.component.html',
  styleUrls: ['./finance-oldchange-list.component.scss']
})
export class FinanceOldchangeListComponent implements OnInit {
  @ViewChild('followUpRef') followUpRef: any;
  @ViewChild('SearchRef') SearchRef: any;

  searchTabs: Array<any> = [
    {value: 1, label: '配件商城'},
    {value: 2, label: '二手商城'}
  ];
  tabsIndex: number = 0;

  searchOptions = [
    { type: 1, labelText: '销售单订单号', valueKey: 'saleOrderNum', value: '' },
    {
      type: 2,
      labelText: '订单状态',
      valueKey: 'saleOrderStatusList',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...partsOrderStatusArrs],
    },
    { type: 1, labelText: '旧机订单号', valueKey: 'recycleOrderNum', value: '' },
    {
      type: 2,
      labelText: '补贴状态',
      valueKey: 'statusList',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...financeOrderChangeArrs],
    },
    { type: 3, labelText: '更新时间', valueKey: ['beginUpdateTime', 'endUpdateTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  /**
   * 修改收款信息 Modal
   * ----------------------------------------------------------------
   */
  isCollectionVisible = false;
  collectionLoading = false;
  collectionForm!: FormGroup;

  // 打款
  isPaymentVisible: boolean = false;
  paymentReasons: any = [
    { value: 1, label: '用户未添加收款信息' },
    { value: 2, label: '收款信息错误' }
  ];
  paymentForm!: FormGroup;

  // 跟进 Modal
  initParams: any = {
    type: 1, // type  1、订单 2、售后 3、客户 4、出库 5、直降 6、退税 7、机器 8、商品
    // modelId: 2, // 类型 1、旧的表示二手回收 2、表示二手商城 3、表示二手回收
    relationInformation: ''
  };
  // export
  exportLoading = false;

  /**
   * ----------------------------------------------------------------
   * Table Check
   * ----------------------------------------------------------------
   */
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private modal: NzModalService,
    private commonService: CommonService,
    private services: FinanceOldchangeManageService
  ) { }

  ngOnInit(): void {
    // 修改收款信息
    this.collectionForm = this.fb.group({
      id: [''],
      payacc: [null, [Validators.required]],
      payname: [null, [Validators.required]]
    });

    // 打款失败
    this.paymentForm = this.fb.group({
      note: ['', [Validators.required]]
    });
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      isType: this.tabsIndex,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getOrderChangeListData(params);
    this.tableParams.loading = false;

    if (code === 0) {
      this.tableParams.tableData = data?.records || [];
      this.tableParams.total = data?.total || 0;
    } else {
      this.msg.error(message);
    }
  }

  queryResetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  tabsChange({index, tab}: any) {
    let tempIndex = this.searchOptions.findIndex(item => item.valueKey === 'saleOrderStatusList');
    this.searchOptions[tempIndex].selectOptions = this.tabsIndex === 0 ? [...partsOrderStatusArrs] : [...secondOrderStateArrs];

    this.tabsIndex = index;
    this.checked = false;
    this.indeterminate = false;
    this.setOfCheckedId.clear();
    this.tableParams.page = 1;
    this.SearchRef.resetSearch();
  }

  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          isType: this.tabsIndex,
          ...this.searchParams
        }
        this.exportLoading = true;
        const res: any = await this.services.exportFindExcelData(params);
        this.exportLoading = false;
    
        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, `财务以旧换机${this.tabsIndex === 0 ? '配件' : '二手'}订单管理`);
        } else {
          this.msg.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  // 跟进
  followModal(item: any) {
    this.initParams.relationInformation = item.id;
    this.initParams.type = this.tabsIndex === 0 ? 8 : 12;
    this.followUpRef.isModelVisible = true;
  }

  // 生成补贴
  generateSubsidies(item: any) {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: `是否要${item.status === 1 ? '重新' : ''}生成补贴，生成后财务将进行打款`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          isType: this.tabsIndex,
          id: item.id,
          state: 1
        }
        const {code, message}: any = await this.services.generateSubsidiesData(params);
        if (code === 0) {
          this.loadTable();
          this.msg.success('操作成功');
        } else {
          this.msg.error(message);
        }
      },
      nzCancelText: '取消'
    });
  }

  /**
   * ----------------------------------------------------------------
   * 修改收款信息
   * ----------------------------------------------------------------
   */
  showCollectionModal(item: any) {
    this.collectionForm.reset();
    this.collectionForm.patchValue({
      id: item.id,
      payacc: item.payacc,
      payname: item.payname
    })
    this.isCollectionVisible = true;
  }

  async subCollection() {
    if (this.collectionForm.valid) {
      let params = {
        isType: this.tabsIndex,
        ...this.collectionForm.value
      }
      this.collectionLoading = true;
      const {code, message}: any = await this.services.updateCollectionInfosData(params);
      this.collectionLoading = false;

      if (code === 0) {
        this.isCollectionVisible = false;
        this.msg.success('操作成功');
        this.loadTable();
      } else {
        this.msg.error(message);
      }
    } else {
      Object.values(this.collectionForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * ----------------------------------------------------------------
   * 打款 成功 | 失败
   * ----------------------------------------------------------------
   */

  // 原因选择
  reasonChange(value: any) {
    // let tmpObj = this.paymentReasons.find((item: any) => item.value == value);
    // this.paymentForm.get('remarks')?.setValue(tmpObj.label);
  }

  // Show Modal 打款失败
  showPaymentModal() {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需操作项');
      return
    }
    this.paymentForm.reset();
    this.isPaymentVisible = true;
  }

  // 打款成功 | 失败
  subPayment(type: number) {
    if (!this.setOfCheckedId.size) {
      this.msg.warning('请先选择所需操作项');
      return
    }
    let params = {
      isType: this.tabsIndex,
      ids: [...this.setOfCheckedId],
      status: type // 0-待生成、1-待打款、2-打款完成、3-打款失败
    }

    switch (type) {
      case 3:
        let failParams = {
          ...params,
          ...this.paymentForm.value
        }

        if (this.paymentForm.valid) {
          this.paymentInterface(failParams, type);
        } else {
          Object.values(this.paymentForm.controls).forEach(control => {
            if (control.invalid) {
              control.markAsDirty();
              control.updateValueAndValidity({ onlySelf: true });
            }
          });
        }
        return;
      case 2:
        this.paymentInterface(params, type);
        return;
    }
  }

  /**
   * 打款失败 | 成功(改为：发放补贴)
   * @param params 
   * @param type 2：成功 3：失败
   */
  paymentInterface(params: any, type?: number) {
    let tipStr = type === 3 ? '是否要将所勾选的订单标记为打款失败' : '是否发放补贴，确认后补贴将原路返回用户支付账户';
    
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: tipStr,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        const res: any = await this.services.paymentData(params);
        this.isPaymentVisible = false;
        if (res.code === 0) {
          this.loadTable();
          this.msg.success(res.data);
        } else {
          this.msg.error(res.message);
        }
      },
      nzCancelText: '取消'
    });
  }
}
